package org.lanqiao.music.web.controller;

import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.lanqiao.music.common.dto.LoginDTO;
import org.lanqiao.music.common.exp.*;
import org.lanqiao.music.common.utils.RateLimit;
import org.lanqiao.music.common.utils.Result;
import org.lanqiao.music.system.entity.User;
import org.lanqiao.music.system.service.UserService;
import org.lanqiao.music.system.utils.JWTUtil;
import org.lanqiao.music.system.utils.RedisUtils;
import org.lanqiao.music.system.vo.LoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api")
public class LoginController {
    @Autowired
    UserService userService;
    @Autowired
    private RedisUtils redisUtils;
    @Value("${sys.login.code}")
    private String codePrefix;
    @Value("${file.upload}")
    private String uploadUrl;

    @RequestMapping("login")
    public Result login(@RequestBody LoginDTO dto){
        try {
            System.out.println("userName:"+dto.getUsername());
            System.out.println("password:"+dto.getPassword());
            System.out.println("key:"+dto.getKey());
            System.out.println("code:"+ dto.getCode());
            Object code = redisUtils.get(codePrefix+":"+dto.getKey());
            System.out.println("code:"+ code);
            User user = userService.Login(dto,code);
            //token有效期1天
            String token = JWTUtil.getToken(user, 1);
            LoginVO loginVO = new LoginVO();
            loginVO.setUserId(user.getUserId());
            System.out.println("id是"+user.getUserId());
            loginVO.setUserName(user.getUserName());
            loginVO.setHead(user.getHead());
            loginVO.setNickName(user.getNickName());
            loginVO.setSex(user.getSex());
            loginVO.setEmail(user.getEmail());
            loginVO.setBirthday(user.getBirthday());
            loginVO.setIsDelete(user.getIsDelete());
            loginVO.setToken(token);
            System.out.println("logincontroller输出的token"+token);
            return Result.success(loginVO);
        }catch (CaptchaNullException e){
            e.printStackTrace();
            return Result.fail(5001,e.getMessage());//5001验证码为空
        }catch (CaptchaExpiredException e){
            e.printStackTrace();
            return Result.fail(5002,e.getMessage());//5002验证码过期
        }catch (CaptchaErrorException e){
            e.printStackTrace();
            return Result.fail(5003,e.getMessage());//5003验证码错误
        }catch (AccountNullException e){
            return Result.fail(5004,e.getMessage());//5004 账号不存在
        }catch (AccountErrorException e){
            return Result.fail(5005,e.getMessage());//5005 账号或密码错误
        }
    }
    @RequestMapping("register")
    public Result register(@RequestBody User user){
        System.out.println(user);
        try {
            User u = userService.insert(user);
            if (u!=null){
                return Result.success("注册成功",u);
            }
            return Result.fail(5010,"注册失败");
        }catch (UsernameNullException e){
            e.printStackTrace();
            return Result.fail(5006,e.getMessage());//5006 用户名不能为空
        }catch (PasswordNullException e){
            e.printStackTrace();
            return Result.fail(5007,e.getMessage());//5007 密码不能为空
        }catch (SexNullException e){
            e.printStackTrace();
            return Result.fail(5008,e.getMessage());//5008 性别不能为空
        }catch (NickNameNullException e){
            e.printStackTrace();
            return Result.fail(5009,e.getMessage());//5009 昵称不能为空
        }

    }

    /**
     * 注册时头像上传
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("upload")
    public Result uploadHeader(MultipartFile file) throws IOException {
        String fileName=file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf('.'));
        fileName = UUID.randomUUID().toString().replaceAll("-", "")+suffix;
        File f = new File(uploadUrl,fileName);
        file.transferTo(f);
        return Result.success("上传成功",fileName);

    }

    /**
     * 产生验证码
     * @param request
     * @param response
     * @return
     */
    // 60秒内最多允许调用5次
    @RequestMapping("captcha")
    public Result captcha(HttpServletRequest request, HttpServletResponse response){
        //请求头设为图片类型
        response.setContentType("image/gif");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        // 设置宽、高、位数
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
        //设置字体
        specCaptcha.setFont(new Font("Verdana", Font.PLAIN, 32));
        // 设置类型，纯数字、纯字母、字母数字混合
        specCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER);
        System.out.println(specCaptcha.text().toLowerCase());
        //存入redis
        String key = codePrefix+":"+ UUID.randomUUID().toString();
        String uuid =UUID.randomUUID().toString();
        redisUtils.set( codePrefix+":"+uuid,specCaptcha.text().toLowerCase(),120, TimeUnit.SECONDS);
        // 输出图片流
        //specCaptcha.out(response.getOutputStream());
        //返回给客户端对象
        Map<String,String> map = new HashMap<>();
        map.put("captchaKey",uuid);
        map.put("captcha",specCaptcha.toBase64());
        return Result.success("success",map);


    }

}
